<script setup lang="ts">
import { reactive, ref, onMounted, watch } from 'vue';
import { spaceApi } from '@T2/service/api.ts';
import { deepCopy } from '@T2/utils/utils.ts';
import type Node from 'element-plus/es/components/tree/src/model/node';
import type { ElTree } from 'element-plus';

interface SpaceType {
  id: number;
  name: string;
  parent: null | number;
  project: number;
  type: '楼栋';
  [key: string]: any;
}
interface TreeNode {
  id: number;
  name: string;
  project?: number;
  type?: '楼栋';
  children?: SpaceType[];
  [key: string]: any;
}
const emits = defineEmits<{
  (event: 'current-change', data: TreeNode, node: Node): void;
  (event: 'spacelist-change', tree: SpaceType[]): void;
}>();

const Resd = reactive({
  tree: [] as TreeNode[],
  filterText: '',
  currentSpaceID: null as null | number,
});
onMounted(() => {
  Promise.all([loadSpaceList()]).then((res: any) => {
    emits('spacelist-change', deepCopy(res[0]));
    Resd.tree = [{ id: 0, name: '全部', children: res[0] }] as TreeNode[];
    if (res[0].length) {
      setTimeout(() => {
        treeRef.value!.setCurrentKey(res[0][0].id);
      }, 100);
    }
  });
});
const loadSpaceList = () => {
  return new Promise((resolve, reject) => {
    spaceApi({
      method: 'get',
      params: {
        ordering: 'create_time',
        type: '楼栋',
      },
    }).then((res: any) => {
      resolve(res.results || []);
    }).catch(e => {
      reject(e);
    });
  });
}

const treeRef = ref<InstanceType<typeof ElTree> | null>(null);
watch(() => Resd.filterText, (nv) => {
  treeRef.value!.filter(nv);
});
const filterNode = (value: string, data: TreeNode, node: Node) => {
  if (!value) {
    return true;
  }
  let obj = data, parentNode = node.parent, names: string[] = [];
  for(let level = node.level; level > 0; level--) {
    names = [...names, obj.name];
    obj = parentNode.data as TreeNode;
    parentNode = parentNode.parent;
  }
  return names.some(name => name.indexOf(value) !== -1);
}
const handleChange = (data: TreeNode, node: Node) => {
  if (data.hasOwnProperty('parent')) {
    Resd.currentSpaceID = data.id as number;
    emits('current-change', data, node);
  }
}
</script>

<template>
  <div class="tree flex-column">
    <el-input v-model="Resd.filterText" placeholder="输入名称进行筛选..." >
      <template #suffix>
        <el-icon><Search /></el-icon>
      </template>
    </el-input>
    <el-tree
      ref="treeRef"
      class="scroller-aside"
      node-key="id"
      :highlight-current="true"
      :props="{label: 'name', disabled: 'disabled'}"
      :data="Resd.tree"
      :indent="15"
      :filter-node-method="filterNode"
      @current-change="handleChange"
    >
      <template #default="{ node, data }">
        <div
          class="el-tree-node__label"
          :style="{color: data.disabled ? 'rgba(18,30,52,0.4)' : Resd.currentSpaceID === data.id ? '#4D92F5' : 'rgba(18,30,52,0.8)'}"
        >
          {{ node.label }}
        </div>
      </template>
    </el-tree>
  </div>
</template>

<style lang="scss" scoped>
.tree {
  width: 220px;
  height: 100%;
  position: relative;
  padding: 20px;
}
</style>

<style scoped>
:deep(.el-input) {
  margin-bottom: 8px;
}
:deep(.el-input__wrapper) {
  box-shadow: none;
  border-bottom: 1px solid rgba(0,0,0,0.1);
  border-radius: 0;
}
:deep(.el-input__inner) {
  color: #121E34;
}

:deep(.el-tree) {
  flex: 1;
  overflow: overlay;
  overflow-x: hidden;
  border-radius: 3px;
  padding: 4px 0;
}
:deep(.is-current>.el-tree-node__content) {
  background-color: #F1F4FA !important;
}
:deep(.el-tree .el-icon) {
  margin-right: 4px;
}
:deep(.el-tree .el-tree-node__label) {
  font-size: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  position: relative;
}
</style>